package com.educatioin.manage.wechat.controller;

import com.educatioin.manage.common.beans.Response;
import com.educatioin.manage.web.studytours.po.ProductPo;
import com.educatioin.manage.web.studytours.po.StudyAbroadProductPo;
import com.educatioin.manage.web.studytours.po.StudyToursProductPo;
import com.educatioin.manage.web.studytours.repository.StudyAbroadProductRepository;
import com.educatioin.manage.web.studytours.repository.StudyToursProductRepository;
import com.educatioin.manage.web.system.po.CustomerPo;
import com.educatioin.manage.web.system.po.CustomerProductCollectPo;
import com.educatioin.manage.web.system.po.CustomerProductShoppingCartPo;
import com.educatioin.manage.web.system.repository.CustomerProductCollectRespository;
import com.educatioin.manage.web.system.repository.CustomerProductShoppingCartRespository;
import com.educatioin.manage.web.system.repository.CustomerRepository;
import com.educatioin.manage.wechat.request.QueryProductsReq;
import com.educatioin.manage.wechat.response.GetStudyAbroadProductByIdRsp;
import com.educatioin.manage.wechat.response.GetStudyToursProductByIdRsp;
import com.educatioin.manage.wechat.response.QueryProductsRsp;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangchen on 2018/3/7.
 */
@RestController
@RequestMapping("/wx/api/product")
public class WeChatProductController {

    @Resource
    private StudyToursProductRepository studyToursProductRepository;
    @Resource
    private StudyAbroadProductRepository studyAbroadProductRepository;
    @Resource
    private CustomerRepository customerRepository;
    @Resource
    private CustomerProductCollectRespository customerProductCollectRespository;
    @Resource
    private CustomerProductShoppingCartRespository customerProductShoppingCartRespository;

    /**
     * 获取游学产品列表
     * @param queryProductsReq
     * @return
     */
    @RequestMapping("/queryStudyToursProducts")
    @ResponseBody
    public QueryProductsRsp queryStudyToursProducts(QueryProductsReq queryProductsReq) {
        QueryProductsRsp queryProductsRsp = new QueryProductsRsp();

        Integer page = queryProductsReq.getPage();
        Integer limit = queryProductsReq.getLimit();

        if(null == page || null == limit){
            queryProductsRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            queryProductsRsp.setReturnMsg("分页参数错误！");
            return queryProductsRsp;
        }

        if(page > 0) {
            page = page -1;
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageRequest = new PageRequest(page, limit, sort);

        String name = queryProductsReq.getName();
        String generation = queryProductsReq.getGeneration();
        String country = queryProductsReq.getCountry();

        Page<StudyToursProductPo> retPage = studyToursProductRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if(StringUtils.isNoneBlank(name)) {
                predicates.add(cb.and(cb.like(root.get("name"), "%" + name + "%")));
            }
            if(StringUtils.isNoneBlank(generation)) {
                predicates.add(cb.and(cb.equal(root.get("generation"), generation)));
            }
            if(StringUtils.isNoneBlank(country)) {
                predicates.add(cb.and(cb.equal(root.get("country"), country)));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);

        if(retPage.hasContent()) {
            List<ProductPo> list = new ArrayList<>();
            list.addAll(retPage.getContent());
            queryProductsRsp.setData(list);
        }
        queryProductsRsp.setCount((int)retPage.getTotalElements());
        queryProductsRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        return queryProductsRsp;
    }

    /**
     * 根据Id获取游学产品详情
     * @param studyToursProductId
     * @return
     */
    @RequestMapping("/getStudyToursProductById")
    @ResponseBody
    public GetStudyToursProductByIdRsp getStudyToursProductById(HttpServletRequest request, Long studyToursProductId) {
        GetStudyToursProductByIdRsp getStudyToursProductByIdRsp = new GetStudyToursProductByIdRsp();

        StudyToursProductPo studyToursProductPo = studyToursProductRepository.findOne(studyToursProductId);
        if(null == studyToursProductPo){
            getStudyToursProductByIdRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            getStudyToursProductByIdRsp.setReturnMsg("产品不存在！");
            return getStudyToursProductByIdRsp;
        }

        Object loginPhone = request.getSession().getAttribute("loginPhone");
        if(null != loginPhone && StringUtils.isNotBlank(loginPhone.toString())){
            CustomerPo customerPo = customerRepository.findByPhone(loginPhone.toString());
            if(null != customerPo){
                CustomerProductCollectPo customerProductCollectPo = customerProductCollectRespository.findByCustomerIdAndProductId(customerPo.getId(), studyToursProductId);
                CustomerProductShoppingCartPo customerProductShoppingCartPo = customerProductShoppingCartRespository.findByCustomerIdAndProductId(customerPo.getId(), studyToursProductId);
                if(null != customerProductCollectPo){
                    getStudyToursProductByIdRsp.setIsCollected(1);
                }
                if(null != customerProductShoppingCartPo){
                    getStudyToursProductByIdRsp.setIsShoppingCart(1);
                }
            }
        }

        getStudyToursProductByIdRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        getStudyToursProductByIdRsp.setStudyToursProductPo(studyToursProductPo);
        //调用查询接口获取数据
        return getStudyToursProductByIdRsp;
    }

    /**
     * 获取留学产品列表
     * @param queryProductsReq
     * @return
     */
    @RequestMapping("/queryStudyAbroadProducts")
    @ResponseBody
    public QueryProductsRsp queryStudyAbroadProducts(QueryProductsReq queryProductsReq) {
        QueryProductsRsp queryProductsRsp = new QueryProductsRsp();

        Integer page = queryProductsReq.getPage();
        Integer limit = queryProductsReq.getLimit();

        if(null == page || null == limit){
            queryProductsRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            queryProductsRsp.setReturnMsg("分页参数错误！");
            return queryProductsRsp;
        }

        if(page > 0) {
            page = page -1;
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageRequest = new PageRequest(page, limit, sort);

        String name = queryProductsReq.getName();
        String generation = queryProductsReq.getGeneration();
        String country = queryProductsReq.getCountry();

        Page<StudyAbroadProductPo> retPage = studyAbroadProductRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if(StringUtils.isNoneBlank(name)) {
                predicates.add(cb.and(cb.like(root.get("name"), "%" + name + "%")));
            }
            if(StringUtils.isNoneBlank(generation)) {
                predicates.add(cb.and(cb.equal(root.get("generation"), generation)));
            }
            if(StringUtils.isNoneBlank(country)) {
                predicates.add(cb.and(cb.equal(root.get("country"), country)));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);

        if(retPage.hasContent()) {
            List<ProductPo> list = new ArrayList<>();
            list.addAll(retPage.getContent());
            queryProductsRsp.setData(list);
        }
        queryProductsRsp.setCount((int)retPage.getTotalElements());
        queryProductsRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        return queryProductsRsp;
    }

    /**
     * 根据Id获取留学产品详情
     * @param studyAbroadProductId
     * @return
     */
    @RequestMapping("/getStudyAbroadProductById")
    @ResponseBody
    public GetStudyAbroadProductByIdRsp getStudyAbroadProductById(HttpServletRequest request,Long studyAbroadProductId) {
        GetStudyAbroadProductByIdRsp getStudyAbroadProductByIdRsp = new GetStudyAbroadProductByIdRsp();

        StudyAbroadProductPo studyAbroadProductPo = studyAbroadProductRepository.findOne(studyAbroadProductId);
        if(null == studyAbroadProductPo){
            getStudyAbroadProductByIdRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            getStudyAbroadProductByIdRsp.setReturnMsg("产品不存在！");
            return getStudyAbroadProductByIdRsp;
        }

        Object loginPhone = request.getSession().getAttribute("loginPhone");
        if(null != loginPhone && StringUtils.isNotBlank(loginPhone.toString())){
            CustomerPo customerPo = customerRepository.findByPhone(loginPhone.toString());
            if(null != customerPo){
                CustomerProductCollectPo customerProductCollectPo = customerProductCollectRespository.findByCustomerIdAndProductId(customerPo.getId(), studyAbroadProductId);
                CustomerProductShoppingCartPo customerProductShoppingCartPo = customerProductShoppingCartRespository.findByCustomerIdAndProductId(customerPo.getId(), studyAbroadProductId);
                if(null != customerProductCollectPo){
                    getStudyAbroadProductByIdRsp.setIsCollected(1);
                }
                if(null != customerProductShoppingCartPo){
                    getStudyAbroadProductByIdRsp.setIsShoppingCart(1);
                }
            }
        }
        getStudyAbroadProductByIdRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        getStudyAbroadProductByIdRsp.setStudyAbroadProductPo(studyAbroadProductPo);
        //调用查询接口获取数据
        return getStudyAbroadProductByIdRsp;
    }
}
